package cn.com.homeyoda.aimate.aihealth.ui.videoinspect;

import static com.wzq.mvvmsmart.utils.Utils.getContext;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.ADD_FAMILY_MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.UPDATE_MEMBER;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.hh.timeselector.timeutil.datedialog.DateListener;
import com.hh.timeselector.timeutil.datedialog.TimeConfig;
import com.hh.timeselector.timeutil.datedialog.TimeSelectorDialog;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.utils.GlideLoadUtils;
import com.wzq.mvvmsmart.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.FamilyMembersBean;
import cn.com.homeyoda.aimate.aihealth.bean.ReplenishChronicBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityImproveInfoBinding;
import cn.com.homeyoda.aimate.aihealth.utils.StringUtils;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

//完善信息
public class ImproveInfoActivity extends BaseActivity<ActivityImproveInfoBinding, VideoInspectModel>{

    int type = 0;
    private File photoFile;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int PERMISSIONS_REQUEST_CODE = 100;
    private ChronicAdapter chronicAdapter;
    private List<String> stringList = new ArrayList<>();
    private String  bingShi = "";
    String reportId;//检测报告id
    String faceId;
    String avatar = "";
    private FamilyMembersBean.DataBean.FamilyMembers member;
    private List<ReplenishChronicBean.DataBean> replenishChronicBeanList = new ArrayList<>();
    public static void start(Context context, FamilyMembersBean.DataBean.FamilyMembers member) {
        Intent starter = new Intent(context, ImproveInfoActivity.class);
        starter.putExtra(MEMBER, member);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    public VideoInspectModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(VideoInspectModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        reportId = getIntent().getStringExtra("reportId");
        faceId = getIntent().getStringExtra("faceId");
        member = getIntent().getParcelableExtra(MEMBER);
        initMemberView();
        initView();
        viewModel.chronicList("");
    }

    private void initMemberView() {
        if (member != null) {
            binding.tvTitle.setText(getString(R.string.member_info));
            avatar = member.getAvatar();
            faceId = member.getFaceId();
            GlideLoadUtils.loadImg(binding.head, avatar, R.mipmap.ic_member1);
            binding.name.setText(member.getName());
            binding.sex.setText(member.getStringSex());
            binding.birthday.setText(member.getBirthday());
            binding.height.setText(member.getHeight());
            binding.weight.setText(member.getWeight());
            if (member.getChronics().contains(",")) {
                String[] chronics = member.getChronics().split(",");
                stringList.addAll(Arrays.asList(chronics));
            }
            binding.buchong.setText(member.getReplenishChronic());
        }
    }

    private void initView() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 设置日期格式
        TimeSelectorDialog dialog = new TimeSelectorDialog(this);
        //设置标题
        dialog.setTimeTitle("选择时间:");
        //显示类型
        dialog.setIsShowtype(TimeConfig.YEAR_MONTH_DAY);
        //默认时间
        if (member == null || TextUtils.isEmpty(member.getBirthday())) {
            dialog.setCurrentDate(df.format(new Date()));
        } else {
            dialog.setCurrentDate(member.getBirthday());
        }
        //隐藏清除按钮
        dialog.setEmptyIsShow(false);
        //设置起始时间
        dialog.setStartYear(1949);
        dialog.setTextSize(14);
        dialog.setSubmitTextColor(R.color.black);
        dialog.setCancleTextColor(R.color.black);
        dialog.setDateListener(new DateListener() {
            @Override
            public void onReturnDate(String time,int year, int month, int day, int hour, int minute, int isShowType) {
                binding.birthday.setText(time);
            }
            @Override
            public void onReturnDate(String empty) {
                binding.birthday.setText(empty);
            }
        });



        chronicAdapter = new ChronicAdapter(R.layout.bingshi_item,replenishChronicBeanList,getApplicationContext());
        binding.setLayoutManager(new GridLayoutManager(getApplicationContext(),3));
        binding.setAdapter(chronicAdapter);

        chronicAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                chronicAdapter.toggleSelection(position);
                //bingShi = stringList.get(position);

            }
        });



        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.show();
            }
        });

        binding.sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showGenderDialog();
            }
        });

        binding.camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchTakePictureIntent();
            }
        });

        binding.save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Set<String> aaa = chronicAdapter.getSelectedString();
                String result = String.join(",", aaa);
                Log.i("huahua","result===="+result);

                if(type > 0){
                    finish();
                }else{
                    if(binding.name.getText().toString().equals("")){
                        Toast.makeText(ImproveInfoActivity.this,"请填写昵称！",Toast.LENGTH_SHORT).show();
                    }else if(binding.sex.getText().equals("请选择")){
                        Toast.makeText(ImproveInfoActivity.this,"请选择性别！",Toast.LENGTH_SHORT).show();
                    }else if(binding.birthday.getText().equals("请选择")){
                        Toast.makeText(ImproveInfoActivity.this,"请选择生日！",Toast.LENGTH_SHORT).show();
                    }else if(binding.height.getText().toString().equals("")){
                        Toast.makeText(ImproveInfoActivity.this,"请填写身高！",Toast.LENGTH_SHORT).show();
                    }else if(binding.weight.getText().toString().equals("")){
                        Toast.makeText(ImproveInfoActivity.this,"请填写体重！",Toast.LENGTH_SHORT).show();
                    }else{
                        JsonObject params = new JsonObject();
                        params.addProperty("faceId", TextUtils.isEmpty(faceId) ? viewModel.getFaceId() : faceId);
                        params.addProperty("name", binding.name.getText().toString());
                        params.addProperty("avatar", avatar);
                        String sex = "";
                        if(binding.sex.getText().toString().equals("男")){
                            sex = "1";
                        }else if(binding.sex.getText().toString().equals("女")){
                            sex = "2";
                        }
                        params.addProperty("sex", sex);
                        params.addProperty("birthday", binding.birthday.getText().toString());
                        params.addProperty("height", binding.height.getText().toString());
                        params.addProperty("weight", binding.weight.getText().toString());
                        params.addProperty("chronics", result);
                        params.addProperty("replenishChronic", binding.buchong.getText().toString());
                        viewModel.updateInfo(params);

                    }



                }


            }
        });


    }



    // 弹出性别选择对话框
    private void showGenderDialog() {
        final String[] genders = {"男", "女", "取消"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择性别");
        builder.setItems(genders, (dialog, which) -> {
            if (which < 2) { // 0=男, 1=女, 2=取消
                String selectedGender = genders[which];
                binding.sex.setText(selectedGender);
            }
        });
        builder.show();
    }


    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  // prefix
                ".jpg",         // suffix
                storageDir      // directory
        );

        // Save a file: path for use with ACTION_VIEW intents
        photoFile = image;

        // Return the file
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            try {
                photoFile = createImageFile();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("huage","requestCode===="+requestCode+"=====resultCode==="+resultCode);
        Log.i("huage","photoFile==222=="+photoFile.getAbsolutePath());
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Log.i("huage","photoFile===="+photoFile.getAbsolutePath());
            if (photoFile != null && photoFile.exists()) {
                Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                binding.head.setImageBitmap(bitmap);
                uploadFile(photoFile.getAbsolutePath());

            } else {
                // Handle the case where the file doesn't exist as expected
            }
        }
    }

    public void uploadFile(String path) {
        //uploadResultList = new ArrayList<>();
        List<File> files = new ArrayList<>();
        //for (String path : attachList) {
        files.add(new File(path));

        //}
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("", "");
        //注意，file是后台约定的参数，如果是多图，file[]，如果是单张图片，file就行
        for (File file : files) {
            try {
                if (file.exists()) {
                    //判断文件是否是jpg图片
                    if (file.getName().contains(".jpg")) {
                        //小于1024kb直接添加
                        builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("*/*"), file));

                    } else {
                        //非图片直接添加
                        builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("*/*"), file));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        RequestBody requestBody = builder.build();
        viewModel.uploadFile(requestBody);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDestroy() {
        super.onDestroy();

    }



    @Override
    public void initViewObservable() {
        viewModel.stateChronicData.observe(this, replenishChronicBean -> {
            replenishChronicBeanList = replenishChronicBean;
            chronicAdapter.setNewData(replenishChronicBeanList);
            for (int i = 0; i < replenishChronicBeanList.size(); i++) {
                String name = replenishChronicBeanList.get(i).getName();
                if (stringList.contains(name)) {
                    chronicAdapter.toggleSelection(i);
                }
            }
        });

        viewModel.updateInfoData.observe(this, replenishChronicBean -> {
            if (TextUtils.isEmpty(reportId)) {
                if (member == null) {
                    LiveEventBus.get(ADD_FAMILY_MEMBER).post(true);
                    ToastUtils.showShort("信息保存成功");
                } else {
                    member.setAvatar(avatar);
                    member.setName(binding.name.getText().toString());
                    member.setSex(TextUtils.equals(binding.sex.getText().toString(), "男") ? 1 : 2);
                    member.setBirthday(binding.birthday.getText().toString());
                    member.setHeight(binding.height.getText().toString());
                    member.setWeight(binding.weight.getText().toString());
                    for (int i = 0; i < replenishChronicBeanList.size(); i++) {
                        String name = replenishChronicBeanList.get(i).getName();
                        if (stringList.contains(name)) {
                            chronicAdapter.toggleSelection(i);
                        }
                    }
                    member.setChronics(String.join(",", chronicAdapter.getSelectedString()));
                    member.setReplenishChronic(binding.buchong.getText().toString());
                    LiveEventBus.get(UPDATE_MEMBER).post(member);
                    ToastUtils.showShort("信息修改成功");
                }
            } else {
                Intent intent = new Intent(getContext(), DetectionResultActivity.class);
                intent.putExtra("reportId", reportId);
                intent.putExtra("faceId", faceId);
                startActivity(intent);
            }
            finish();
        });

        viewModel.stateChronicData.observe(this,replenishChronicBean -> {
            replenishChronicBeanList = replenishChronicBean;
            chronicAdapter.setNewData(replenishChronicBeanList);
        });

        viewModel.uploadFileData.observe(this,uploadFileBean -> {
            avatar = uploadFileBean.getData().getUrl();
        });

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_improve_info;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
